package de.michaelhuebl.demo;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Contacts.People;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import de.michaelhuebl.demo.helper.HttpClientHelper;
import de.michaelhuebl.demo.helper.ParseXmlWithDom;
import de.michaelhuebl.demo.helper.UrlConnectionHelper;
import de.michaelhuebl.demo.helper.parseXmlWithSax;

public class HttpXmlDemo extends Activity { 
	private String url1;
	private String url2;
	private String xmlOutput = "";
	private long counter_start = 0;
	private long counter_end = 0;
	private ArrayList<Location> locations = new ArrayList<Location>();
	
    private Button btn_urlconnection;
    private Button btn_httpclient;
    private Button btn_dom;
    private Button btn_sax;
    private TextView txt_xmloutput;
    private TextView txt_exectime;
    private TextView txt_xmlexectime;
    private TextView txt_parsedtext;
    private ProgressDialog pd;
    
    private final static int CONNECTED_WITH_API = 1;
    private final static int CONNECTED_WITH_URLCONNECTION = 2;
    private final static int PARSED_WITH_SAX = 3;
    private final static int PARSED_WITH_DOM = 4;
    
    private Handler handler = new Handler();

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Instantiate View elements
        btn_httpclient = (Button) findViewById(R.id.main_btn_httpclient);
        btn_httpclient.setOnClickListener(httpClientListener);

        btn_urlconnection = (Button) findViewById(R.id.main_btn_urlconnection);
        btn_urlconnection.setOnClickListener(urlConnectionListener);
        
        btn_sax = (Button) findViewById(R.id.main_btn_sax);
        btn_sax.setOnClickListener(saxListener);
        
        btn_dom = (Button) findViewById(R.id.main_btn_dom);
        btn_dom.setOnClickListener(w3cListener);
        
        txt_xmloutput = (TextView) findViewById(R.id.main_txt_xmloutput);
        txt_exectime = (TextView) findViewById(R.id.main_txt_exectime);
        txt_xmlexectime = (TextView) findViewById(R.id.main_txt_xmlexectime);
        txt_parsedtext = (TextView) findViewById(R.id.main_txt_parsedtext);
        
        
        //Init variables
        url1 = "http://local.yahooapis.com/LocalSearchService/V3/localSearch?appid=YahooDemo&query=pizza&zip=94306&results=4";
        url2 = "http://local.yahooapis.com/LocalSearchService/V3/localSearch?appid=YahooDemo&query=sushi&zip=94306&results=4";
        
    }
	
	
	
	@Override
	protected void onStart() {
		super.onStart();
		//Debug.startMethodTracing("HttpXmlDemo");
	}


	@Override
	protected void onStop() {
		super.onStop();
		//Debug.stopMethodTracing();
	}



	/**
	 * Updates the xml-output view.
	 */
	private Runnable doUpdateXmlOutput = new Runnable() {
		public void run() {
			// Connection to API was successful. 
			// Display the result and stop the ProgressDialog
			txt_xmloutput.setText(xmlOutput);
			txt_exectime.setText( (counter_end - counter_start) + " ms" );
			pd.dismiss();
		}
	};
	
	/**
	 * Updates parsed text view.
	 * Displays the result from parsed XML.
	 */
	private Runnable doUpdateParsedText = new Runnable() {
		public void run() {
			String output = "";
			
			for (int i = 0; i < locations.size(); i++) {
				String title = locations.get(i).getTitle();
				String url = locations.get(i).getBusinessClickUrl();
				output += title;
				if (url != null && url != "")
					output += ": "+url;
				output += "\n";
			}
			
			txt_parsedtext.setText(output);
			txt_xmlexectime.setText( (counter_end - counter_start) + " ms" );
			pd.dismiss();
		}
	};
	
	/**
	 * Calls the HttpClientHelper class to perform
	 * a get request to Yahoo!-API with HTTPClient.
	 * Saves the result in xmlOutput.
	 */
	private Runnable doConnectWithHttpClient = new Runnable() {
		public void run() {
			String result = null;
			
			counter_start = System.currentTimeMillis();
			
			HttpClientHelper connectionHelper = new HttpClientHelper();
			result = connectionHelper.performGetRequest(url1);	
			
			counter_end = System.currentTimeMillis();
			
			xmlOutput = result;
			//handler.sendEmptyMessage(CONNECTED_WITH_API);
			handler.post(doUpdateXmlOutput);
		}
	};
	
	
	/**
	 * Calls the UrlConnectionHelper class to perform
	 * a get request to Yahoo!-API with URLConnection.
	 * Saves the result in xmlOutput.
	 */
	private Runnable doConnectWithUrlConnection = new Runnable() {
		public void run() {
			String result = null;
			
			counter_start = System.currentTimeMillis();
			
			UrlConnectionHelper connectionHelper = new UrlConnectionHelper();
			result = connectionHelper.performGetRequest(url2);
			
			counter_end = System.currentTimeMillis();
			
			xmlOutput = result;

			handler.post(doUpdateXmlOutput);
		}
	};
	
	
	/**
	 * Parses the xml from Yahoo!-API with SAX
	 */
	private Runnable doParsingWithSax = new Runnable() {
		public void run() {
			counter_start = System.currentTimeMillis();
			
			parseXmlWithSax parser = new parseXmlWithSax();
			parser.parseXml(xmlOutput);
			locations = parser.getParseResult();
			
			counter_end = System.currentTimeMillis();
			
			handler.post(doUpdateParsedText);
		}
	};
	
	/**
	 * Parses the xml from Yahoo!-API with DOM
	 */
	private Runnable doParsingWithDom = new Runnable() {
		public void run() {
			counter_start = System.currentTimeMillis();
			
			ParseXmlWithDom parser = new ParseXmlWithDom();
			parser.parseXml(xmlOutput);
			locations = parser.getParseResult();
			
			counter_end = System.currentTimeMillis();
			
			handler.post(doUpdateParsedText);
		}
	};
	
	
	/**
	 * Listener for the btn_httpclient button.
	 * Resets the previously displayed output and
	 * starts a thread which connects the yahoo! API
	 * with HTTPClient.
	 */
	private OnClickListener httpClientListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			
			// Reset displayed result and start thread
			txt_xmloutput.setText("");
			txt_parsedtext.setText("");
			
			pd = ProgressDialog.show(HttpXmlDemo.this, "Please wait...", "Connecting local.yahooapis.com", true, false);
			
			Thread t = new Thread(null, doConnectWithHttpClient, "ConnectWithHttpClient");
			t.start();
		}
	};
	
	/**
	 * Listener for the btn_urlconnection button.
	 * Resets the previously displayed output and
	 * starts a thread which connects the yahoo! API
	 * with URLConnection.
	 */
	private OnClickListener urlConnectionListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			
			// Reset displayed result and start counter
			txt_xmloutput.setText("");
			txt_parsedtext.setText("");
			
			pd = ProgressDialog.show(HttpXmlDemo.this, "Please wait...", "Connecting local.yahooapis.com", true, false);
			
			Thread t = new Thread(null, doConnectWithUrlConnection, "ConnectWithUrlConnection");
			t.start();
		}
		
	};
	
	
	/**
	 * Listener for the btn_w3c Button.
	 * Starts parsing the XML.
	 */
	private OnClickListener saxListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			
			pd = ProgressDialog.show(HttpXmlDemo.this, "Please wait...", "Parsing XML with SAX", true, false);
			
			Thread t = new Thread(null, doParsingWithSax, "ParsingWithSax");
			t.start();
		}
	};
	
	
	/**
	 * Listener for the btn_dom Button.
	 * Starts parsing the XML.
	 */
	private OnClickListener w3cListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			pd = ProgressDialog.show(HttpXmlDemo.this, "Please wait...", "Parsing XML with DOM", true, false);
			
			Thread t = new Thread(null, doParsingWithDom, "ParsingWithDom");
			t.start();
			
		}
	};
	
	
}